package com.wetask.daoImpl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.wetask.dao.UserDao;
import com.wetask.domain.model.SearchResult;
import com.wetask.domain.model.User;
import com.wetask.utils.DaoHelper;

@Repository
public class UserDaoImpl extends DaoHelper<User> implements UserDao{

	@Override
	public User getUserByEmail(String email, String role) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT * FROM user U left join role R on U.role_id = R.id ");
		sql.append("WHERE U.email = ? AND R.role_code = ?");
		Object[] parameters = new Object[]{email, role};
		SearchResult<User> result = query(sql.toString(), parameters, new UserRowMapper());
		if(result.getSearchResult().size() == 0) return null;
		return result.getSearchResult().get(0);
	}

	@SuppressWarnings("rawtypes")
	class UserRowMapper implements RowMapper{
		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			User user = new User();
			user.setId(rs.getInt("id"));
			user.setUsername(rs.getString("username"));
			user.setPassword(rs.getString("password"));
			user.setEmail(rs.getString("email"));
			user.setRoleId(rs.getInt("role_id"));
			user.setEmail(rs.getString("email"));
			return user;
		}
	}
	
}
